/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.amitycs.collabdrawing.client;

import java.awt.Shape;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.amitycs.collabdrawing.Constants;
import org.amitycs.collabdrawing.Whiteboard;
import org.amitycs.collabdrawing.server.Server;

/**
 *
 * @author joe
 */
public class Client {

    private Listener listener;
    private MulticastSocket multisock;
    private Whiteboard whiteboard;
    
    public Client(Whiteboard wb) {
        whiteboard = wb;
        initClient();
    }

    private void initClient() {
        try {
            multisock = new MulticastSocket(Constants.GROUP_PORT);
            multisock.joinGroup(InetAddress.getByName(Constants.GROUP_IP));
        } catch (IOException ex) {
            Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
        }

        listener = new Listener();
        new Thread(listener).start();

    }
    
    public void kill() {
        listener.kill();
        multisock.close();
    }

    public void sendShape(Shape shape) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);
        out.writeObject(shape);
        out.flush();
        bos.flush();
        byte[] bytes = bos.toByteArray();
        out.close();
        bos.close();

        DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
                InetAddress.getByName(Constants.GROUP_IP), Constants.GROUP_PORT);
        multisock.send(packet);
        System.out.println("sent packet");
        
    }

    private class Listener implements Runnable {

        private boolean running = true;

        private void kill() {
            running = false;
        }

        public void run() {
            while (running) {
                try {
                    byte[] buf = new byte[65536];
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    multisock.receive(packet);
                    System.out.println("received packet on client end");
                    ByteArrayInputStream bais = new ByteArrayInputStream(buf);
                    ObjectInputStream ois = new ObjectInputStream(bais);
                    Shape shape = (Shape) ois.readObject();
                    whiteboard.addShape(shape);
                } catch (Exception e) {
                    e.printStackTrace();
                    //ignore
                }
            }
        }
    }
}
